package common.security.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

public class UrlAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	private String adminFailureUrl;
	private String defaultFailureUrl;
	private String ajaxFailureUrl;

	public String getAdminFailureUrl() {
		return adminFailureUrl;
	}

	public void setAdminFailureUrl(String adminFailureUrl) {
		this.adminFailureUrl = adminFailureUrl;
	}

	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		String defaultFailureUrl = this.getDefaultFailureUrl();
		if ("true".equals(request.getParameter("isAdmin"))) {
			defaultFailureUrl = getAdminFailureUrl();
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(request.getHeader("Accept")) && request.getHeader("Accept").contains("application/json")) {
			defaultFailureUrl = getAjaxFailureUrl();
		}
		
		
		if (defaultFailureUrl == null) {
			logger.debug("No failure URL set, sending 401 Unauthorized error");

			response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage());
		} else {
			saveException(request, exception);

			if (isUseForward()) {
				logger.debug("Forwarding to " + defaultFailureUrl);

				request.getRequestDispatcher(defaultFailureUrl).forward(request, response);
			} else {
				logger.debug("Redirecting to " + defaultFailureUrl);
				getRedirectStrategy().sendRedirect(request, response, defaultFailureUrl);
			}
		}
	}

	public String getDefaultFailureUrl() {
		return defaultFailureUrl;
	}

	public void setDefaultFailureUrl(String defaultFailureUrl) {
		this.defaultFailureUrl = defaultFailureUrl;
		super.setDefaultFailureUrl(defaultFailureUrl);
	}

	public String getAjaxFailureUrl() {
		return ajaxFailureUrl;
	}

	public void setAjaxFailureUrl(String ajaxFailureUrl) {
		this.ajaxFailureUrl = ajaxFailureUrl;
	}

}
